package cn.com.egova.mahjong;

import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.suke.widget.SwitchButton;

import java.lang.reflect.Method;
import java.util.Random;

import cn.com.egova.mahjong.bean.MahjongBO;
import cn.com.egova.mahjong.dao.MahjongDao;
import cn.com.egova.mahjong.inter.ICallBack;
import cn.com.egova.mahjong.util.MahjongTool;

public class HomeActivity extends BaseActivity implements View.OnClickListener {
    private String typeName;
    private TextView tvTitle;
    private LinearLayout llContent;
    private TextView tvAnswer;
    private SwitchButton sbShow;
    private Button btnPre;
    private Button btnNext;
    private MahjongDao dao;
    private MahjongTool tool;
    private boolean hasShow = false; //是否显示了题目
    private MahjongBO curMahjongBO;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);

        initData();

        initView();

        loadData(1);
    }

    private void initData() {
        typeName = getIntent().getStringExtra("typeName");
        setTitle(typeName);
    }


    private void initView() {
        tvTitle = (TextView) findViewById(R.id.tv_title);
        llContent = (LinearLayout) findViewById(R.id.ll_content);
        tvAnswer = (TextView) findViewById(R.id.tv_answer);
        sbShow = (SwitchButton) findViewById(R.id.sb_show);
        btnPre = findViewById(R.id.btn_pre);
        btnNext = findViewById(R.id.btn_next);

        sbShow.setOnCheckedChangeListener(new SwitchButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(SwitchButton view, boolean isChecked) {
                tvAnswer.setVisibility(isChecked ? View.VISIBLE : View.GONE);
            }
        });
        btnPre.setOnClickListener(this);
        btnNext.setOnClickListener(this);
    }

    private void loadData(int id) {
        dao = new MahjongDao(typeName);
        tool = new MahjongTool(this, dao);
        this.curMahjongBO = dao.queryById(id);
        hasShow = showSubject(curMahjongBO);
    }

    private boolean showSubject(MahjongBO mahjongBO) {
        if (mahjongBO != null) {
            llContent.setVisibility(View.VISIBLE);
            tvTitle.setText(mahjongBO.getType() + ":第" + mahjongBO.getDisplayOrder() + "题");
            tvAnswer.setText(mahjongBO.getTing());
            tool.showWithImages(llContent, mahjongBO);
            return true;
        } else {
            tvAnswer.setText("");
            llContent.setVisibility(View.GONE);
        }
        return false;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_pre:
                goPre();
                break;
            case R.id.btn_next:
                goNext();
                break;
        }
    }

    private void goPre() {
        if (curMahjongBO == null) {
            makeToast("当前题库为空！");
            return;
        }
        MahjongBO preBO = dao.getPreData(curMahjongBO);
        if (preBO == null) {
            makeToast("已经是第一道题！");
        } else {
            curMahjongBO = preBO;
            showSubject(preBO);
        }
    }


    private void goNext() {
        if (curMahjongBO == null) {
            Toast.makeText(this, "当前题库为空！", Toast.LENGTH_SHORT).show();
            makeToast("当前题库为空！");
            return;
        }
        MahjongBO nextBO = dao.getNextData(curMahjongBO);
        if (nextBO == null) {
            makeToast("已经是最后一道题！");
        } else {
            curMahjongBO = nextBO;
            showSubject(nextBO);
        }
    }


    @Override
    public boolean isBackIconVisible() {
        return true;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        setIconEnable(menu, true);  //4.0以后的系统,这一步必须有.
        getMenuInflater().inflate(R.menu.menu_action, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.menu_add:
                tool.addData(typeName, new ICallBack<MahjongBO>() {
                    @Override
                    public void onResult(int index, MahjongBO resultObj) {
                        if (dao.add(resultObj)) {
                            makeToast("添加数据成功！");
                        } else {
                            makeToast("添加数据失败！");
                        }
                        if (!hasShow) {
                            curMahjongBO = resultObj;
                            showSubject(resultObj);
                        }
                    }
                });
                break;
            case R.id.menu_delete:
                //删除当前
                dao.delete(curMahjongBO);
                loadData(curMahjongBO.getId() - 1);
                break;
            case R.id.menu_update:
                tool.updateData(curMahjongBO, new ICallBack<MahjongBO>() {
                    @Override
                    public void onResult(int index, MahjongBO resultObj) {
                        if (dao.update(resultObj)) {
                            makeToast("修改数据成功！");
                        } else {
                            makeToast("修改数据失败！");
                        }
                        curMahjongBO = resultObj;
                        showSubject(resultObj);
                    }
                });
                break;
            case R.id.menu_random:
                int max = dao.getMaxId();
                int random = new Random().nextInt(max);
                loadData(random);
                break;
            case R.id.menu_last:
                loadData(dao.getMaxId());
                break;
        }
        return false;
    }

    /**
     * enable为true时，菜单添加图标有效，enable为false时无效。4.0系统默认无效
     * 底层源码:4.0以后将mOptionalIconsVisible的值默认设置为false了.
     * void setOptionalIconsVisible(boolean visible) {
     * mOptionalIconsVisible = visible;
     * }
     *
     * @param menu   为true时,setIcon()方法生效,否则不生效.
     * @param enable
     */
    private void setIconEnable(Menu menu, boolean enable) {
        try {
            Class<?> clazz = Class.forName("com.android.internal.view.menu.MenuBuilder");
            Method m = clazz.getDeclaredMethod("setOptionalIconsVisible", boolean.class);
            m.setAccessible(true);

            //MenuBuilder实现Menu接口，创建菜单时，传进来的menu其实就是MenuBuilder对象(java的多态特征)
            m.invoke(menu, enable);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private void makeToast(String str) {
        Toast.makeText(HomeActivity.this, str, Toast.LENGTH_SHORT).show();
    }
}
